import {createRouter,createWebHistory} from 'vue-router';
import store from '@/store';
import routesStatic from './routes-static';//静态路由


//动态导入多个模块
const modules = import.meta.glob(["../views/**/*.vue","!../views/**/components/*.vue"]);

const router = createRouter({
    history:createWebHistory(),
    routes:routesStatic,

});


//白名单得路由集合
const whiteNames = ["login",'403','404']

router.beforeEach(async(to,from) => {
    if ( !whiteNames.includes(to.name)) {
        //做登录状态得校验
        //1.获取 token
       const token  = store.state.user.token
        //2.判断 token是否存在
       if( !token) {
        return {
            name : 'login',
            query: {
                redirect : to.fullPath,
            }
        }
       }
      // const routes = store.state.user.routes
       //判断路由权限
    //    if( to.name !== 'index' && !routes.includes(to.path)) {
    //     //没有访问权限
    //     return '/403';
    //    } 
    //获取当前是否动态添加过
    const isAdd = store.state.user.isAdd;   
    //没有添加过时，才需要动态添加
    if(!isAdd) {
        //修改 isAdd 为 true
        store.commit("user/setIsAdd",true);
        //获取用户个人信息 ， 平凡会当前用户的路由权限数据
        const routes = await store.dispatch("user/getPerson");

        routes.forEach((route) => {
            router.addRoute("index", {
                path : route.router,

                component:modules[`../${route.viewPath}`]
            });
        });
        return to.fullPath;
    }
    }
})

export default router